package com.amap.search.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelUtil {
    public static <T>  void setExportExcel(String fileName, List<T>data) throws IOException {
        setExportExcel(fileName, data, "sheet");
    }

    public static  <T> void setExportExcel(String fileName, List<T>data, String sheetName) throws IOException {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getResponse();
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); // 设置http头与文件名
        response.setContentType("application/msexcel;charset=UTF-8"); //设置类型
        response.setCharacterEncoding("utf-8"); // 设置编码
        EasyExcel.write(response.getOutputStream(), data.get(0).getClass()).sheet(sheetName).doWrite(data);
    }
}
